package jp.co.sharp.android.parents.kidsguard.activity.edit;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.List;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.PeriodSettingWeekActivity;
import jp.co.sharp.android.parents.kidsguard.common.DateTimePickerDlg;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

public class AlarmEditActivity extends AppCompatActivity {

    public ParentBleTransfer mParentBleTransfer;
    private App mApp;
    public final int CODE_SUCCEED =200;
    // 選択済み
    private KidInfoEntity mKidInfoEntity;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private LinearLayout repetitionDate;
    private LinearLayout repetitionTime;
    private TextView repetitionDateText;
    private TextView repetitionTimeText;
    // default 1回のみ = -1
    private int repetition = -1;
    private boolean isAdd;
    private Integer hour;
    private Integer minute;
    private int alramId;
    private String voiceName = "なし";
    private int state;
    private JSONArray alarmList;
    private boolean mUnReceiver = true;
    private static final String TAG="TAG";
    private int mPageCode = PageSerialNumConstants.PAGE_SERIAL_ALARM_SETTING;
    private int mViewProcess = 0;
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    // プログラムロック
    private String mSyncLock = "syncLock";
    // 編集を再開しています...
    private boolean mEditReopening = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "AlarmEditActivity_onCreate");
        setContentView(R.layout.activity_alarm_edit);
        initReceiver();
        initActivity();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "AlarmEditActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }
    @Override
    protected void onStop() {
        Log.i(TAG, "AlarmEditActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onStop();
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "AlarmEditActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if (mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT) {
                    toopenDig();
                }
                mSystemHomeFlag = false;
            }
        }
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "AlarmEditActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onDestroy();
    }
    private void initActivity() {
        Log.i(TAG, "AlarmEditActivity_initActivity");
        TextView textView = (TextView)findViewById(R.id.settingSecondMenu);
        String strSecondMenu = mKidInfoEntity.getKidName() + "のキッズケータイ";
        textView.setText(strSecondMenu);
        initPageDate();
        repetitionTimeText.setText(getCurrentDate());
        repetitionTime.setOnTouchListener((View view, MotionEvent motionEvent)->{
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                initDateModule();
                return true;
            }
            return false;
        });
        repetitionDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                mPageJumpFlag = true;
                Intent intent = new Intent();
                intent.setClass(AlarmEditActivity.this, PeriodSettingWeekActivity.class);
                intent.putExtra("repetition", repetition);
                startActivityForResult(intent, 1);
            }
        });
        LinearLayout mSound = findViewById(R.id.sound);
        mSound.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                mPageJumpFlag = true;
                Intent intent = new Intent();
                intent.setClass(AlarmEditActivity.this, AlarmListActivity.class);
                intent.putExtra("voiceName",voiceName);
                startActivityForResult(intent, 2);

            }
        });
        ImageView addPeriodSetting = findViewById(R.id.addPeriodSetting);
        addPeriodSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Dlg
                String message = "キッズケータイへ反映中..";
                mDealWithWaitingDlg = new DealWithWaitingDlg(AlarmEditActivity.this, R.style.commonDlg, message, true);
                mDealWithWaitingDlg.show();
                setKidAlarms(false);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "AlarmEditActivity_onActivityResult");
        initReceiver();
        if (resultCode == CODE_SUCCEED) {
            if (requestCode == 1) {
                //处理回调相关操作
                repetition = data.getIntExtra("repetition", 0);
                loadRepetitionData(repetition);
            } else if (requestCode == 2) {
                //处理回调相关操作
                voiceName = data.getStringExtra("voiceName");
                TextView soundText = findViewById(R.id.soundText);
                soundText.setText(voiceName);

            }
        }
    }

    private void loadRepetitionData(int repetition) {
        String repeatText = "1回のみ";
        if (repetition > 1) {
            List<String> repetitionList = AlarmActivity.repetitionToStirng(Integer.toHexString(repetition));
            StringBuffer contentText = new StringBuffer();
            for (String week : repetitionList) {
                contentText.append(week);
                contentText.append(" ");
            }
            repeatText = contentText.toString();
        }
        repetitionDateText.setText(repeatText);
    }

    private void initPageDate() {
        Intent intent = getIntent();
        try {
            alarmList = new JSONArray(intent.getStringExtra("alarmList"));
            alramId = intent.getIntExtra("alramId", -1);
            if (alramId == -1) {
                popupLog("異常な操作!");
            }
            isAdd = intent.getBooleanExtra("isAdd", true);
            if (isAdd) {
                ImageView imageView = findViewById(R.id.deletePeriodSetting);
                imageView.setVisibility(View.GONE);
                Calendar now = Calendar.getInstance();
                hour = now.get(Calendar.HOUR_OF_DAY);
                minute = now.get(Calendar.MINUTE);
                state = 0;
            } else {
                for (int i = 0; i < alarmList.length(); i++) {
                    JSONObject alarmI = alarmList.getJSONObject(i);
                    Integer id = alarmI.getInt("id");
                    if (id == alramId) {
                        state = alarmI.getInt("state");
                        String time = alarmI.getString("time");
                        String[] timeArr = time.split(":");
                        hour = Integer.valueOf(timeArr[0]);
                        minute = Integer.valueOf(timeArr[1]);
                        voiceName = alarmI.getString("soundName");
                        repetition = alarmI.getInt("repetition");
                        TextView soundText = findViewById(R.id.soundText);
                        soundText.setText(voiceName);
                        loadRepetitionData(repetition);
                    }
                }
                ImageView deletePeriodSetting = findViewById(R.id.deletePeriodSetting);
                deletePeriodSetting.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String message = "このアラームを削除しますか？";
                        DelDeviceConfirmDlg mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(AlarmEditActivity.this, R.style.commonDlg, message);
                        mDelDeviceConfirmDlg.show();
                        mDelDeviceConfirmDlg.setOnOperateSetListener(new DelDeviceConfirmDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                // Dlg
                                String message = "キッズケータイへ反映中..";
                                mDealWithWaitingDlg = new DealWithWaitingDlg(AlarmEditActivity.this, R.style.commonDlg, message, true);
                                mDealWithWaitingDlg.show();
                                setKidAlarms(true);
                            }
                        });
                    }
                });
            }
        } catch (Exception e) {
             Log.e(TAG, e.getMessage());
            popupLog("異常な操作!");
        }
    }

    private void initReceiver() {
        this.repetitionDateText = this.findViewById(R.id.repetitionDateText);
        this.repetitionDate = this.findViewById(R.id.repetitionDate);
        this.repetitionTimeText = this.findViewById(R.id.repetitionTimeText);
        this.repetitionTime = this.findViewById(R.id.repetitionTime);
        // init
        mApp = (App) getApplication();
        mKidInfoEntity = mApp.findKidInfoBySelect();
        IntentFilter filter = new IntentFilter();
        // ロック画面
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        // 画面を開く
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer(); mUnReceiver = false;

    }

   

    public void backActivity(View view) {
        AlarmEditActivity.this.finish();
    }

    private String getCurrentDate() {
        Integer thishour = hour;
        String prefix = "午前";
        if (thishour >= 12) {
            prefix = "午後";
            thishour = Math.abs(thishour - 12);
        }
        return prefix + intCovering(thishour) + ":" + intCovering(minute);
    }

    private void initDateModule() {
        Integer thishour = hour;
        int prefix = 0;
        if (thishour >= 12) {
            prefix = 1;
            thishour = Math.abs(thishour - 12);
        }
        DateTimePickerDlg dateTimePickerDlg = new DateTimePickerDlg(AlarmEditActivity.this, R.style.commonDlg, prefix, thishour, minute);
        dateTimePickerDlg.show();
        dateTimePickerDlg.setOnDateTimeSetListener(new DateTimePickerDlg.OnDateTimeSetListener() {
            @Override
            public void onDateTimeSet(int pAmPm, int pHour, int pMinute) {
                String prefix = "午前";
                hour = pHour;
                if (pAmPm == 1) {
                    prefix = "午後";
                    hour += 12;
                }
                minute=pMinute;
                repetitionTimeText.setText(prefix +intCovering(pHour)  + ":" + intCovering(minute));
            }
        });
    }
    private String intCovering(int num){
        String numString = num+"";
        if (num < 10) {
            numString = "0" + numString;
        }
        return numString;
    }
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                String retStr = bluetoothReceiverDto.getRetStr();
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(retStr);
//                    System.out.println("json："+jsonObject);
                    if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(jsonObject.getString("method"))) {
                        if (jsonObject.getString("result").equals(Constants.ON_SYNC_RESULT)) {
                            mDealWithWaitingDlg.dismiss();
                            AlarmEditActivity.this.setResult(CODE_SUCCEED);//200代表成功
                            AlarmEditActivity.this.finish();
                        }else {
                            popupLog("操作に失敗する!");
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                }
            }else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                if (bluetoothReceiverDto.isFinished()) {
                    switch (mViewProcess) {
                        case Constants.SEND_KID_ENTER:
                            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                                mEditReopening = false;
                                mDealWithWaitingDlg.dismiss();
                            }
                            break;
                    }
                }
            }
        }
    };
    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                synchronized (mSyncLock) {
                    mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                    mViewProcess = Constants.SEND_KID_EXIT;
                    new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                }
            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                synchronized (mSyncLock) {
                    mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                    if (!mPageJumpFlag) {
                        toopenDig();
                    }
                }
            } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                synchronized (mSyncLock) {
                    mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                    mSystemHomeFlag = true;
                    mViewProcess = Constants.SEND_KID_EXIT;
                    new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                }
            } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                // 初期化
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                String macAddress = bluetoothReceiverDto.getAddress();
                if (mApp.isMimamoriCheck(macAddress)) {
                    mApp.addmLsIsMimamori(macAddress);
                    mViewProcess = Constants.SEND_KID_EXIT;
                    new BusinessThread(Constants.SEND_KID_EXIT, mPageCode, mParentBleTransfer, mKidInfoEntity).start();
                    // ページジャンプ
                    mPageJumpFlag = true;
                    Intent intent1 = new Intent();
                    intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                    intent1.setClass(AlarmEditActivity.this, HomeActivity.class);
                    startActivity(intent1);
                } else {
                    mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                    ((App) getApplication()).updateKidInfo(mKidInfoEntity);

                    String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                    ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(AlarmEditActivity.this, R.style.commonDlg, message);
                    processWarringDlg.show();
                    processWarringDlg.setOnOperateSetListener(() -> {
                        processWarringDlg.dismiss();
                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setClass(AlarmEditActivity.this, EditActivity.class);
                        startActivity(intent1);
                    });
                }
            }
        }
    };
    private void popupLog(String message) {
        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(AlarmEditActivity.this, R.style.commonDlg, message);
        processWarringDlg.show();
        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
            @Override
            public void onOperateSet() {
                processWarringDlg.dismiss();
                AlarmEditActivity.this.finish();
            }
        });
    }

    private void setKidAlarms(boolean isDelete) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_SET_ALARMS);
            JSONObject jsonData = new JSONObject();
            JSONObject alarm = new JSONObject();
            if (isAdd) {
                alarmList.put(alarm);
            } else {
                for (int i = 0; i < alarmList.length(); i++) {
                    JSONObject alarmI = alarmList.getJSONObject(i);
                    Integer id = alarmI.getInt("id");
                    if (id == alramId) {
                        if(isDelete){
                            alarmList.remove(i);
                        }else {
                            alarm = alarmI;
                        }
                    }
                }
            }
            if(isDelete){
                JSONArray deleteList=new JSONArray();
                deleteList.put(alramId);
                jsonData.put("deleteList", deleteList);
            }else {
                alarm.put("id", alramId);
                alarm.put("repetition", repetition);
                alarm.put("soundName", voiceName);
                alarm.put("state", state);

                alarm.put("time", intCovering(hour) + ":" + intCovering(minute));
            }
            jsonData.put("alarmList", alarmList);
            jsonObject.put("data", jsonData);
            mParentBleTransfer.writeLeData(mKidInfoEntity.getMacAddress(), jsonObject.toString());

        } catch (Exception e) {
             Log.e(TAG, e.getMessage());
        }
    }
    private void toopenDig() {
        if (!mEditReopening) {
            String message = "編集を再開しています...";
            mDealWithWaitingDlg = new DealWithWaitingDlg(AlarmEditActivity.this, R.style.commonDlg, message, false);
            mDealWithWaitingDlg.show();
            mViewProcess = Constants.SEND_KID_IS_USING;
            new BusinessThread(Constants.SEND_KID_IS_USING,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    null,
                    PageSerialNumConstants.PAGE_SERIAL_NUM_POWER_SETTING).start();
            // ブロードキャストの再登録
            unregisterReceiver(systemReceiver);
            initReceiver();
            mEditReopening = true;
        }
    }
}
